package br.com.gr.jcash.relatorio;

import br.com.gr.jcash.util.JcashResources;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

/**
 *
 * @author gelson
 */
public class GeradorRelatorio {
    private JcashResources resources;

    public GeradorRelatorio() {
        this.resources = JcashResources.getInstance();
    }

    public void gerarRelatorioWeb(List lista, String nomeRelatorio, HashMap<String, Object> parametros) throws IOException, JRException {
        String path = resources.getProperty(nomeRelatorio);
        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(lista);
        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath(path);
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, parametros, beanCollectionDataSource);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\""
                + nomeRelatorio + "-"
                + new SimpleDateFormat("dd-MM-yyyy_HH_mm").format(new Date())
                + ".pdf" + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }
}